package gorm

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"

	// "gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// DBService is a database engine object.
type DBService struct {
	Default *gorm.DB            // the default database engine
	List    map[string]*gorm.DB // database engine list
}

func getDialector(driver, connstring string) gorm.Dialector {
	switch driver {
	case "mysql":
		return mysql.Open(connstring)
	case "postgres", "postgresql":
		return postgres.Open(connstring)
	// case "sqlite3", "sqlite":
	//	return sqlite.Open(connstring)
	default:
		panic(fmt.Sprintf("[gorm] unsupported driver: %s", driver))
	}
}

func fileExists(filename string) bool {
	_, err := os.Stat(filename)
	return !os.IsNotExist(err)
}

var dbService = func() (serv *DBService) {
	serv = &DBService{
		List: map[string]*gorm.DB{},
	}

	var errs []string
	defer func() {
		if len(errs) > 0 {
			panic("[gorm] " + strings.Join(errs, "\n"))
		}
		if serv.Default == nil {
			panic("[gorm] the `default` database engine must be configured and enabled")
		}
	}()

	err := loadDBConfig()
	if err != nil {
		panic(fmt.Sprintf("[gorm] %s", err.Error()))
	}

	for _, conf := range dbConfigs {
		if !conf.Enable {
			continue
		}

		dialector := getDialector(conf.Driver, conf.Connstring)
		engine, err := gorm.Open(dialector, &gorm.Config{})
		if err != nil {
			log.Printf("[gorm] %s", err.Error())
			errs = append(errs, err.Error())
			continue
		}

		// Configure logger for GORM v2
		if conf.ShowSql {
			engine.Logger = logger.Default.LogMode(logger.Info)
		} else {
			engine.Logger = logger.Default.LogMode(logger.Silent)
		}

		sqlDB, err := engine.DB()
		if err != nil {
			log.Printf("[gorm] %s", err.Error())
			errs = append(errs, err.Error())
			continue
		}
		sqlDB.SetMaxOpenConns(conf.MaxOpenConns)
		sqlDB.SetMaxIdleConns(conf.MaxIdleConns)

		if (conf.Driver == "sqlite3" || conf.Driver == "sqlite") && !fileExists(conf.Connstring) {
			os.MkdirAll(filepath.Dir(conf.Connstring), 0777)
			f, err := os.Create(conf.Connstring)
			if err != nil {
				log.Printf("[gorm] %s", err.Error())
				errs = append(errs, err.Error())
			} else {
				f.Close()
			}
		}

		serv.List[conf.Name] = engine
		if DEFAULTDB_NAME == conf.Name {
			serv.Default = engine
		}
	}
	return
}()
